<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="!avatar" class="the_img" src="@/assets/boate.jpg" alt="" />
      <img v-else :src="avatar" class="the_img" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" accept="image/*" style="display: none" ref="iptRef" @change="onFileChange" />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="updateFn">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
import { updateUserAvatarAPI } from '@/api/index'
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    // 选择图片的点击事件
    chooseImg () {
      this.$refs.iptRef.click()
    },
    // 选择图片确定了
    onFileChange (e) {
      const files = e.target.files
      // eslint-disable-next-line no-empty
      if (files.length === 0) {
        this.avatar = ''
      } else {
        // console.log(files[0])
        // this.avatar = URL.createObjectURL(files[0])
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = e => {
          this.avatar = e.target.result
        }
      }
    },
    async updateFn () {
      const res = await updateUserAvatarAPI(this.avatar)
      if (res.data.code !== 0) return this.$message.success(res.data.message)
      this.$message.success(res.data.message)
      this.$store.dispatch('getUserInfoActions')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
.the_img{
    width: 300px;
    height: 300px;
    background-color: rgb(240, 213, 229);
    font-size: 40px;
    line-height: 300px;
    text-align: center;
}
</style>
